package com.millstein.educenter.controller;

import com.millstein.educenter.WxConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/api/ucenter/wx")
@CrossOrigin
@EnableConfigurationProperties(WxConfig.class)
public class WxApiController {

    @Autowired
    private WxConfig wxConfig;
    /**
     * 生成微信扫描的二维码
     * @return
     */
    @GetMapping("login")
    public String getWxCode() {
        // 固定地址，准备模板。%s相当于占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect"
                + "?appid=%s"
                + "&redirect_url=%s"
                + "&response_type=code"
                + "&scope=snsapi_login"
                + "&state=%s"
                + "#wechat_redirect";

        // 对redirect_url进行编码
        String redirectUrl = wxConfig.getRedirectUrl();
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 设备%s的值
        String url = String.format(baseUrl, wxConfig.getAppId(), redirectUrl, "millstein");
        System.out.println(url);
        // 重定向到请求微信地址里
        return "redirect:" + url;
    }
}
